import React, { Component } from 'react'
import moment from 'moment'
import { Link } from 'react-router-dom';
import axios from 'axios'
import { List, Button, Skeleton } from 'antd';
import Config from '../config'
require('./index.css')

let pageNum = 1

export default class Order extends Component {

  constructor(props) {
    super(props)
    this.state = {
      orderList: [],
      initLoading: true,
      loading: false,
      pageTotal: 1,
      data: [],
      list: [],
      isData: true
    }
  }

  detail(item) {
    let id = `${item.consumptionName}|${item.num}|${item.totalPrice}|${item.code}|${item.state}|${item.orderTime}|${item.payWay}`
    this.props.history.push(`/order/${id}`)
  }

  componentDidMount() {
    document.title = '订单列表'
    this.getData((orderList) => {
      this.setState({
        initLoading: false,
        data: orderList,
        list: orderList,
      });
    });
  }

  onLoadMore = () => {
    pageNum++
    this.setState({
      loading: true,
      list: this.state.data.concat([...new Array(5)].map(() => ({ loading: true, name: {} }))),
    }, () => {
      this.getData((orderList) => {
        const data = this.state.data.concat(orderList);
        this.setState({
          data,
          list: data,
          loading: false,
        }, () => {
          window.dispatchEvent(new Event('resize'));
        });
      });
    });
  }

  getData = (callback) => {
    let openId = localStorage.getItem('openId') || 'huacao1'

    if (pageNum <= this.state.pageTotal || pageNum === 1) {
      axios.get(`${Config.Fetch.orderList}?createUser=${openId}&pageNo=${pageNum}&pageSize=10`,
      ).then(response => {
        if (response.data.success) {
          let orderList = response.data.rows
          let pageTotal = Math.ceil(parseInt(response.data.total) / 10)
          callback(orderList);
          this.setState({
            orderList: orderList,
            pageTotal
          }, () => {
            this.setState({ loading: false })
          })
        }

      }).catch(error => {
        alert(JSON.stringify(error))
        console.log(error)
      })
      pageNum === this.state.pageTotal && pageNum !== 1 ? this.setState({ isData: false }) : null
    }
  }

  render() {
    const { initLoading, loading, list, isData } = this.state;
    const loadMore = !initLoading && !loading ? (
      <div style={{ textAlign: 'center', marginTop: 12, height: 32, lineHeight: '32px' }}>
        {isData ? <Button onClick={this.onLoadMore.bind(this)}>加载更多</Button> : <div>没有更多数据</div>}
      </div>
    ) : null;

    return (
      <div style={{ marginBottom: 20 }}>
        <div style={{ height: 30, marginBottom: 30 }}>
          <Link to={`../SellTicket`} style={{ margin: '20px 20px 20px', float: 'right' }}>预订</Link>
        </div>
        <List
          className="demo-loadmore-list"
          loading={initLoading}
          itemLayout="horizontal"
          loadMore={loadMore}
          dataSource={list}
          renderItem={item => (
            <List.Item >
              <Skeleton title={false} loading={item.loading} active paragraph={{ rows: 2 }}>
                <div className='order-container' onClick={this.detail.bind(this, item)}>
                  <div className='order-product'>{item.consumptionName}<span style={{ fontSize: 14 }}> x {item.num}</span></div>
                  <div className='order-price'>¥ {item.totalPrice}</div>
                  <div className='order-time'>{moment(new Date(item.orderTime)).format('YYYY-MM-DD hh:mm:ss')}</div>
                  <div className='order-status'>{item.state}</div>
                </div>
              </Skeleton>
            </List.Item>
          )}
        />
      </div>
    )
  }
}
